package com.zh.harmony.mvvm.slice;

import com.zh.harmony.lifecycle.Lifecycle;
import com.zh.harmony.lifecycle.LifecycleOwner;
import com.zh.harmony.viewmodel.ViewModelStore;
import com.zh.harmony.viewmodel.ViewModelStoreOwner;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;

/**
 * 支持ViewModel的AbilitySlice
 */
public class ComponentAbilitySlice extends AbilitySlice implements LifecycleOwner, ViewModelStoreOwner {
    private ViewModelStore mViewModelStore;

    @Override
    protected void onStop() {
        super.onStop();
        Ability ability = getAbility();
        //销毁时，没有发生配置重建时，才清理ViewModelStore
        if (mViewModelStore != null && !ability.isUpdatingConfigurations()) {
            mViewModelStore.clear();
        }
    }

    @Override
    public ViewModelStore getViewModelStore() {
        Ability ability = getAbility();
        if (ability == null) {
            throw new NullPointerException("ability must be not null");
        }
        if (ability.getAbilityPackage() == null) {
            throw new IllegalStateException("Your ability is not yet attached to the "
                    + "AbilityPackage instance. You can't request ViewModel before onStart call.");
        }
        if (mViewModelStore == null) {
            mViewModelStore = new ViewModelStore();
        }
        return mViewModelStore;
    }

    @Override
    public Lifecycle getLifeCycle() {
        return ((LifecycleOwner) getAbility()).getLifeCycle();
    }
}